<?php

/**
 * @filename DefaultController.php
 * @author qiankun <wankang@dodoca.com>
 * @datetime 2016/4/21 13:53
 * @description 会员
 */
class Member_DefaultController extends SellerController
{
    /**
     * @author zouhao <zouhao@dodoca.net>
     * @description 会员列表
     * @datetime 2016年4月21日13:53:12
     */
    public function indexAction()
    {
        //基本条件
        $params = $this->_request->getQuery();
        $page = max(1, intval($params['page']));

        $pageSize = 10;
        $shopId = $this->getCurrentUser()->getShopId();
        
        $sellerId = $this->getCurrentUser()->getSellerId();
        $params['seller_id'] = $sellerId;
        if(!$this->getCurrentUser()->isChiefShop())
        {
            $params['shop_id'] = $shopId;
            $fansWhere['shop_id'] = $shopId;
        }
        else 
        {
        	$shopId = 0;
        }
        $importModel = new Statistics_MemberImportModel();
        $memberImportFileModel = new Statistics_MemberImportFileModel();
        
        $cardList = User_CardService::getListBySellerId($sellerId);
        $payCardList = User_CardService::getExpireMemberListBySellerId($sellerId);
        $shopFansModel = new U_ShopFansModel($sellerId);
        $fansWhere['seller_id'] = $sellerId;
        $fansArr = $shopFansModel->select($fansWhere, array('fans_id'));
        $fansIdArr = array();
        if(!empty($fansArr)) {
            foreach($fansArr as $key => $value){
                $fansIdArr[] = $value['fans_id'];
            }
        }
        if(!empty($fansIdArr)){
            $couponCount = Deposit_CouponService::getPersonalCouponReceiveList($fansIdArr, $shopId, $sellerId);
        }
        $data = WeiXin_WxUserService::getMemberList($params, $page, $pageSize);
        $count = $data['total'];
        $totalPage = ceil($count/$pageSize);
        Tool_Log::info('member_total','member_total',array('count'=>$count,'totalPage'=>$totalPage));
        $list = $data['list'];
        if(!empty($list))
        {
        	$shop = $this->getCurrentUser()->getShop();
        	if($shop['consumption_status'] == 1 || $this->getCurrentUser()->isChiefShop())
        	{
        		$shopId = $this->getCurrentUser()->getChiefShopId();
        		$fansIdArr = array();
        		foreach ($list as $k=>$v)
        		{
        			$fansIdArr[] = $v['fans_id'];
        		}
        		 
        		$shopFansInfo = $shopFansModel->select(array('fans_id'=>array('in',$fansIdArr),'shop_id'=>$shopId),array('consumption','fans_id','integral'));
        	}
            foreach($list as $k => $v)
            {
            	//查询会员卡名称
            	$cardInfo = '';
            	$cardInfo = User_CardService::getCardInfo($v['card_id']);
            	$list[$k]['card_name'] = $cardInfo['card_name'];
            	if($v['user_info'])
            	{
            		$list[$k]['user_info'] = json_decode($v['user_info'], true);
            	}
                if(!empty($couponCount) && is_array($couponCount))
                {
                    foreach($couponCount as $id => $num)
                    {
                    	if($v['fans_id'] == $num['userid'])
                    	{
                    		$list[$k]['coupon_num'] = $num['total'];
                    	}
                    }
                        
                }
                
                if($shopFansInfo)
                {
                	foreach ($shopFansInfo as $key=>$val)
                	{
                		if($v['fans_id'] == $val['fans_id'])
                		{
                			$list[$k]['consumption'] = $val['consumption'];
                			$list[$k]['shop_integral'] = $val['integral'];
                		}
                	}
                }
            }
        }
        //获得excel基本数据
        $where = array(
            'status' => 2,
            'seller_id' => $sellerId,
            'shop_id' => $this->getCurrentUser()->getShopId()
        );
        if($importFile = $memberImportFileModel->find($where,array('id','create_time'),'id DESC'))
        {
            $importFile['create_time'] = date('Y-m-d H:i', $importFile['create_time']);
            $where = array('import_file_id' => $importFile['id'], 'status' => 2);//成功条数
            $successCount = $importModel->count($where);
            $where = array('import_file_id' => $importFile['id'], 'status' => 3);//失败条数
            $errorCount = $importModel->count($where);
        }
        //获得excel基本数据END
        //获得商户手机号
        $subUserModel = new U_SubUserModel();
        $where = array(
            'seller_id' => $sellerId,
            'type' => array('in','1,2'),
            'status' => 1,
            'phone' => array('neq','')
        );
        $subUser = $subUserModel->select($where,array('id','phone'));
        $coupon = Deposit_CouponService::manualCouponList($this->getCurrentUser()->getShopId(),1,3,'',1,500);

        //判断是否提示验证手机验证码
        $phoneKey = 'qualifiedPhone_' . $this->getCurrentUser()->get('id');
        $phoneKey = mc_get($phoneKey);
        $hasCheckPhone = isset($phoneKey)? 1 : 0;//1为不验证

        $data = array(
            'count' => $count,
            'params' => $params,
            'totalPage' => $totalPage,
            'page' => $page,
            'member_list' => $list,
            'card_list' => $cardList,
            'coupon'=>$coupon['lists'],
            'successCount' => $successCount,
            'errorCount' => $errorCount,
            'importFile' => $importFile,
            'subUser' => $subUser,
            'payCardList' => $payCardList,
            'role' => intval($this->getCurrentUser()->getRole()),
            'hasCheckPhone' => $hasCheckPhone,
            'webUrl' => WEB_DOMAIN
        );
        Tool_Log::info('MemberDefault','MemberDefaultData',$data);
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/default/index.html');
    }


    /**
     * ajax获取userInfo对象
     * @author wankang
     * date 2016年12月19日11:16:52
     */
    public function ajaxGetUserinfoAction()
    {
    	try 
    	{
    		if(!$this->_request->isXmlHttpRequest())
    		{
    			throw new Exception('非法请求');
    		}
    		$id = $this->_request->getPost('uid');
    		if(!$id)
    		{
    			throw new Exception('缺少必要参数');
    		}
    		$memberModel = new U_MemberCardModel();
    		$userInfo = $memberModel->find(array('seller_id'=>$this->getCurrentUser()->getSellerId(),'fans_id'=>$id),array('user_info'));
    		if($userInfo)
    		{
    			$userInfo = json_decode($userInfo, true);
    		}
    		
    		$this->ajaxReturn(array('code'=>1,'msg'=>'success','data'=>$userInfo));
    	}
    	catch (Exception $e)
    	{
    		$this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
    	}
    }
    
    /**
     * @author zouhao <zouhao@dodoca.net>
     * @description 基本信息筛选
     * @datetime 2016年4月21日13:53:12
     */
    public function recordAction()
    {
        //基本条件
        $params = $this->_request->getQuery();
        $page = max(1, intval($params['page']));
        $pageSize = 10;
        $shopId = $this->getCurrentUser()->getShopId();
        $where['shop_id'] = $shopId;
        $sellerId = $this->getCurrentUser()->getSellerId();
        $where['seller_id'] = $sellerId;

        $shopFansModel = new U_ShopFansModel($sellerId);
        $order = 'create_time DESC';
        $memberList = $shopFansModel->listPage($where, array('*'), $order, $page, $pageSize);
        if(!empty($memberList)){
            foreach($memberList as $key => $value){
                $fansId = $value['fans_id'];
                $fansInfo = WeiXin_WxUserService::getFansInfo($fansId, $sellerId);
                $memberList[$key]['fans_info'] = $fansInfo;
                $memberList[$key]['fans_info']['head_img_url'] = $fansInfo['img'];
            }
        }
        $count = $shopFansModel->count;
        $totalPage = ceil($count/$pageSize);
        $data = array(
            'page' => $page,
            'total' => $count,
            'totalPage' => $totalPage,
            'member_list' => $memberList
        );
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/default/record.html');
    }
    
    /**
     * 消费行为筛选
     */
    public function behaviorFilterAction()
    {
        //基本条件
        $params = $this->_request->getQuery();
        $page = max(1, intval($params['page']));
        $pageSize = 10;
        $shopId = $this->getCurrentUser()->getShopId();
        $where['shop_id'] = $shopId;
        $sellerId = $this->getCurrentUser()->getSellerId();
        $where['seller_id'] = $sellerId;

        //筛选条件
//        !empty($params['']) && $where[''] = '';


        $shopFansModel = new U_ShopFansModel($sellerId);
        $order = 'create_time DESC';
        $memberList = $shopFansModel->listPage($where, array('*'), $order, $page, $pageSize);
        if(!empty($memberList)){
            foreach($memberList as $key => $value){
                $fansId = $value['fans_id'];
                $fansInfo = WeiXin_WxUserService::getFansInfo($fansId, $sellerId);
                $memberList[$key]['fans_info'] = $fansInfo;
                $memberList[$key]['fans_info']['head_img_url'] = $fansInfo['img'];
            }
        }
        $count = $shopFansModel->count;
        $totalPage = ceil($count/$pageSize);
        $data = array(
            'total' => $count,
            'page' => $page,
            'totalPage' => $totalPage,
            'member_list' => $memberList
        );
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/default/behavior-filter.html');
    }
    
    
    //提现记录
    public function withdrawRecordAction()
    {
        $this->assign('loadModuleScript', true);
        $this->display(array(), 'member/default/withdraw-record.html');
    }
    
    //提现设置
    public function withdrawSetAction()
    {
        $this->assign('loadModuleScript', true);
        $this->display(array(), 'member/default/withdraw-set.html');
    }
    
    /**
     * 后台送积分和优惠券、消费金
     */
    public function ajaxRewardAction()
    {
        try 
        {
            if($this->getCurrentUser()->getRole() != 2)
            {
                throw new Exception('没有操作权限');
            }
            if(!$this->_request->isXmlHttpRequest())
            {
                throw new Exception('非法请求');
            }
            $postData = $this->_request->getPost();
            if(!$fansId = $postData['fans_id'])
            {
                throw new Exception('缺少粉丝信息');
            }
            if(!$val = $postData['val'])
            {
                throw new Exception('缺少必要参数');
            }
            //验证粉丝和商户的关系
            $action = intval($postData['action']);
            if($action == 2)
            {
            	$val = $val * -1;
            }
            
            $sellerId = $this->getCurrentUser()->getSellerId();
            $shopId = $this->getCurrentUser()->getShopId();
            if(!WeiXin_WxUserService::checkRelation($postData['fans_id'], $sellerId))
            {
            	throw new Exception('无权对此会员进行管理');
            }		
            if($postData['type'] == 1)
            {
                //送积分
            	$remark = $postData['remark'] ? safe_replace($postData['remark']) : ($action == 1 ? '商户赠送' : '商户扣除');
                if(!WeiXin_WxUserService::integralAlter($fansId, $val, $remark, $shopId))
                {
                    throw new Exception('修改积分失败，请稍后再试');
                }
                
            }
            elseif ($postData['type'] == 2)
            {
            	if(!WeiXin_WxUserService::checkRelation($postData['fans_id'], $sellerId, $shopId))
            	{
            		throw new Exception('该用户和当前店铺没有绑定关系');
            	}
                //送消费金
            	$remark = $postData['remark'] ? safe_replace($postData['remark']) : '';
                if(!WeiXin_WxUserService::consumptionAlter($shopId, $fansId, $val, $remark, null, 6, true, true))
                {
                    throw new Exception('修改消费金失败，请稍后再试');
                }
            }
            elseif ($postData['type'] == 3)
            {
                //送优惠券
                Deposit_CouponService::receiveCoupon($val, $fansId,$shopId,0,0,0,true);
            }
            else 
            {
                throw new Exception('未知类型，请稍后再试');
            }
            
            $this->ajaxReturn(array('code'=>1000, 'msg'=>'success'));
        }
        catch (Exception $e)
        {
            $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
        }
    }
}